from flask import Flask, render_template,request, url_for
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
import numpy as np
import matplotlib.pyplot as plt
import plotly as py
import plotly.graph_objs as go
import cufflinks as cf

app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/welcome")
def all():
    # 高校数据分析
    university = pd.read_csv('./高校数据.csv', encoding='gbk')
    junior = pd.read_csv('./专业数据_专科(高职).csv', encoding='gbk')
    regular = pd.read_csv('./专业数据_本科.csv', encoding='gbk')
    university = university.loc[:, ['name', 'nature_name', 'province_name', 'address', 'belong',
                                    'city_name', 'dual_class_name', 'f211', 'f985', 'level_name',
                                    'type_name', 'view_month_number', 'view_total_number',
                                    'view_week_number', 'rank']]
    c_name = ['大学名称', '办学性质', '省份', '地址', '隶属', '城市', '高校层次',
              '211院校', '985院校', '级别', '类型', '月访问量', '总访问量', '周访问量', '排名']
    university.columns = c_name
    e_name = ['name', 'limit_year', 'level1_name', 'level2_name', 'level3_name',
              'degree', 'salaryavg', 'girl_rate', 'view_week', 'view_month', 'view_total']
    regular = regular.loc[:, e_name]
    c_name2 = ['专业名称', '学制', '一级名称', '二级名称', '三级名称', '学位',
               '平均薪资', '女生比例', '周访问量', '月访问量', '总访问量']
    regular.columns = c_name2
    junior = junior.loc[:, e_name]
    junior.columns = c_name2
    university['高校总数'] = 1
    university.fillna({'高校层次': '非双一流'}, inplace=True)
    university_by_province = university.pivot_table(index=['省份', '高校层次'],
                                                    values='高校总数', aggfunc='count')
    university_by_province.reset_index(inplace=True)
    university_by_province.sort_values(by=['高校总数'], ascending=False, inplace=True)
    fig = px.bar(university_by_province,
                 x="省份",
                 y="高校总数",
                 color="高校层次")
    fig.update_layout(
        title='全国各省高校数量',
        xaxis_title="省份",
        yaxis_title="高校总数",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black",
        ),
        height=450,
        width=600,
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
        legend=dict(yanchor="top",
                    y=0.9,
                    xanchor="left",
                    x=0.78)
    )
    py.offline.plot(fig, filename="全国各省高校数量.html", auto_open=False)
    with open("全国各省高校数量.html", encoding="utf8", mode="r") as f:
        plot_all1 = "".join(f.readlines())
    df = pd.read_excel('./全国省市区行政区划.xlsx', header=1)
    df_l = df.query("层级==2").loc[:, ['全称', '经度', '纬度']]
    df_l = df_l.reset_index(drop=True).rename(columns={'全称': '城市'})
    df7 = university.pivot_table('大学名称', '城市', aggfunc='count')
    df7 = df7.merge(df_l, on='城市', how='left')
    df7.sort_values(by='大学名称', ascending=False)
    df7['text'] = df7['城市'] + '<br>大学总数 ' + (df7['大学名称']).astype(str) + '个'
    limits = [(0, 10), (11, 20), (21, 50), (51, 100), (101, 200)]
    colors = ["royalblue", "crimson", "lightseagreen", "orange", "red"]
    cities = []
    scale = .08
    fig = go.Figure()
    for i in range(len(limits)):
        lim = limits[i]
        df_sub = df7[df7.大学名称.map(lambda x: lim[0] <= x <= lim[1])]
        fig.add_trace(go.Scattergeo(
            locationmode='ISO-3',
            lon=df_sub['经度'],
            lat=df_sub['纬度'],
            text=df_sub['text'],
            marker=dict(
                size=df_sub['大学名称'],
                color=colors[i],
                line_color='rgb(40,40,40)',
                line_width=0.5,
                sizemode='area'
            ),
            name='{0} - {1}'.format(lim[0], lim[1])))
    fig.update_layout(
        height=450,
        width=600,
        title_text='全国高校地理分布图',
        showlegend=True,
        geo=dict(
            scope='asia',
            landcolor='rgb(217, 217, 217)',
        ),
        template='ggplot2',
        font=dict(
            size=12,
            color="Black", ),
        legend=dict(yanchor="top",
                    y=0.,
                    xanchor="left",
                    x=0)
    )
    py.offline.plot(fig, filename="全国高校地理分布图.html", auto_open=False)
    with open("全国高校地理分布图.html", encoding="utf8", mode="r") as f:
        plot_all2 = "".join(f.readlines())
    return render_template(
        "welcome.html",
        tu=plot_all1,
        tu1=plot_all2
    )

@app.route('/hot')
def hot():
    # 高校热度分析
    university = pd.read_csv('./高校数据.csv', encoding='gbk')
    junior = pd.read_csv('./专业数据_专科(高职).csv', encoding='gbk')
    regular = pd.read_csv('./专业数据_本科.csv', encoding='gbk')
    university = university.loc[:, ['name', 'nature_name', 'province_name', 'address', 'belong',
                                    'city_name', 'dual_class_name', 'f211', 'f985', 'level_name',
                                    'type_name', 'view_month_number', 'view_total_number',
                                    'view_week_number', 'rank']]
    c_name = ['大学名称', '办学性质', '省份', '地址', '隶属', '城市', '高校层次',
              '211院校', '985院校', '级别', '类型', '月访问量', '总访问量', '周访问量', '排名']
    university.columns = c_name
    e_name = ['name', 'limit_year', 'level1_name', 'level2_name', 'level3_name',
              'degree', 'salaryavg', 'girl_rate', 'view_week', 'view_month', 'view_total']
    regular = regular.loc[:, e_name]
    c_name2 = ['专业名称', '学制', '一级名称', '二级名称', '三级名称', '学位',
               '平均薪资', '女生比例', '周访问量', '月访问量', '总访问量']
    regular.columns = c_name2
    junior = junior.loc[:, e_name]
    junior.columns = c_name2
    university.sort_values(by='总访问量', ascending=False).head()
    import plotly.graph_objs as go
    fig = go.Figure()
    df3 = university.sort_values(by='总访问量', ascending=False)
    fig.add_trace(go.Bar(
        x=df3.loc[:15, '大学名称'],
        y=df3.loc[:15, '总访问量'],
        name='总访问量',
        marker_color='#009473',
        textposition='inside',
        yaxis='y1'
    ))
    fig.add_trace(go.Scatter(
        x=df3.loc[:15, '大学名称'],
        y=df3.loc[:15, '周访问量'],
        name='周访问量',
        mode='markers+text+lines',
        marker_color='black',
        marker_size=10,
        textposition='top center',
        line=dict(color='orange', dash='dash'),
        yaxis='y2'
    ))
    fig.update_layout(
        height=450,
        width=600,
        title='全国高校热度TOP15',
        xaxis_title="大学名称",
        yaxis_title="总访问量",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black",
        ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
        yaxis2=dict(showgrid=True, overlaying='y', side='right', title='周访问量'),
        legend=dict(yanchor="top",
                    y=1.15,
                    xanchor="left",
                    x=0.8)
    )
    py.offline.plot(fig, filename="普通本科全国高校热度TOP15.html", auto_open=False)
    with open("普通本科全国高校热度TOP15.html", encoding="utf8", mode="r") as f:
        plot_all3 = "".join(f.readlines())
    # 专科高校热度
    import plotly.graph_objs as go
    fig = go.Figure()
    df4 = university.query("级别 =='专科（高职）'").sort_values(by='总访问量', ascending=False).iloc[:15, :]
    fig.add_trace(go.Bar(
        x=df4['大学名称'],
        y=df4['总访问量'],
        name='总访问量',
        marker_color='#009473',
        textposition='inside',
        yaxis='y1'
    ))
    fig.add_trace(go.Scatter(
        x=df4['大学名称'],
        y=df4['周访问量'],
        name='周访问量',
        mode='markers+text+lines',
        marker_color='black',
        marker_size=10,
        textposition='top center',
        line=dict(color='orange', dash='dash'),
        yaxis='y2'

    ))
    fig.update_layout(
        height=450,
        width=600,
        title='全国专科(高职)院校热度TOP15',
        xaxis_title="高校名称",
        yaxis_title="总访问量",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black",
        ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
        yaxis2=dict(showgrid=True, overlaying='y', side='right', title='周访问量'),
        legend=dict(yanchor="top",
                    y=1.15,
                    xanchor="left",
                    x=0.8)
    )
    py.offline.plot(fig, filename="全国专科(高职)院校热度TOP15.html", auto_open=False)
    with open("全国专科(高职)院校热度TOP15.html", encoding="utf8", mode="r") as f:
        plot_all15 = "".join(f.readlines())
    # 每省热度前三
    df9 = university.loc[:, ['省份', '大学名称', '总访问量']]
    df9['前三'] = df9.drop_duplicates()['总访问量'].groupby(by=df9['省份']).rank(method='first', ascending=False)
    # 筛选前三名
    df_10 = df9[df9['前三'].map(lambda x: True if x < 4 else False)]
    # 转换数据类型
    df_10['前三'] = df_10.前三.astype(int)
    df_pt = df_10.pivot_table(values='总访问量', index='省份', columns='前三')
    # 排序
    df_pt_2 = df_pt.sort_values(by=1, ascending=False)[:10]
    df_labels_1 = df9[df9.前三 == 1].set_index('省份').loc[df_pt_2.index, '大学名称'][:10]
    df_labels_2 = df9[df9.前三 == 2].set_index('省份').loc[df_pt_2.index, '大学名称'][:10]
    df_labels_3 = df9[df9.前三 == 3].set_index('省份').loc[df_pt_2.index, '大学名称'][:10]
    x = df_pt_2.index
    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=x,
        y=df_pt_2[1],
        name='热度第一',
        marker_color='indianred',
        textposition='inside',
        text=df_labels_1.values,
        textangle=90
    ))
    fig.add_trace(go.Bar(
        x=x,
        y=df_pt_2[2],
        name='热度第二',
        marker_color='lightsalmon',
        textposition='inside',
        text=df_labels_2.values,
        textangle=90
    ))
    fig.add_trace(go.Bar(
        x=x,
        y=df_pt_2[3],
        name='热度第三',
        marker_color='lightpink',
        textposition='inside',
        text=df_labels_3.values,
        textangle=90
    ))
    # Here we modify the tickangle of the xaxis, resulting in rotated labels.
    fig.update_layout(barmode='group', xaxis_tickangle=-45)
    fig.update_layout(
        height=450,
        width=600,
        title='全国高校热度TOP10省份的前三名',
        xaxis_title="省份",
        yaxis_title="总访问量",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black"),
        barmode='group', xaxis_tickangle=-45
    )
    py.offline.plot(fig, filename="全国高校热度TOP10省份的前三名.html", auto_open=False)
    with open("全国高校热度TOP10省份的前三名.html", encoding="utf8", mode="r") as f:
        plot_all10 = "".join(f.readlines())
    # 北京
    df_bj = university.query("高校层次 == '双一流' and 城市== '北京市'").iloc[:15, :]
    ## Plot Region wise countt of countries and average ladder score
    import plotly.graph_objs as go
    fig = go.Figure()
    df3 = university.sort_values(by='总访问量', ascending=False)
    fig.add_trace(go.Bar(
        x=df_bj['大学名称'],
        y=df_bj['总访问量'],
        name='总访问量',
        marker_color='#009473',
        textposition='inside',
        yaxis='y1'
    ))
    fig.add_trace(go.Scatter(
        x=df_bj['大学名称'],
        y=df_bj['周访问量'],
        name='周访问量',
        mode='markers+text+lines',
        marker_color='black',
        marker_size=10,
        textposition='top center',
        line=dict(color='orange', dash='dash'),
        yaxis='y2'
    ))
    fig.update_layout(
        height=450,
        width=600,
        title='北京高校热度TOP15',
        xaxis_title="大学名称",
        yaxis_title="总访问量",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black",
        ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
        yaxis2=dict(showgrid=True, overlaying='y', side='right', title='周访问量'),
        legend=dict(yanchor="top",
                    y=1.15,
                    xanchor="left",
                    x=0.78)
    )
    py.offline.plot(fig, filename="北京高校热度TOP15.html", auto_open=False)
    with open("北京高校热度TOP15.html", encoding="utf8", mode="r") as f:
        plot_all16 = "".join(f.readlines())
    return render_template(
        "hot.html",
        tu2=plot_all3,
        tu15=plot_all15,
        tu10=plot_all10,
        tu16=plot_all16,
    )

hotmajor = [{'本科热门专业':'A'},{'专科(高职)热门专业':'B'}]
@app.route('/hot_major', methods=['GET', 'POST'])
def hot_major():
    # 热门专业
    select = request.form.get('comp_select')
    regular = pd.read_csv('./专业数据_本科.csv', encoding='gbk')
    e_name = ['name', 'limit_year', 'level1_name', 'level2_name', 'level3_name',
              'degree', 'salaryavg', 'girl_rate', 'view_week', 'view_month', 'view_total']
    regular = regular.loc[:, e_name]
    c_name2 = ['专业名称', '学制', '一级名称', '二级名称', '三级名称', '学位',
               '平均薪资', '女生比例', '周访问量', '月访问量', '总访问量']
    regular.columns = c_name2
    import plotly.graph_objs as go
    fig = go.Figure()
    df11 = regular.sort_values(by='总访问量', ascending=False)[:20]
    fig.add_trace(go.Bar(
        x=df11['专业名称'],
        y=df11['总访问量'],
        name='总访问量',
        marker_color='#009473',
        textposition='inside',
        yaxis='y1'
    ))
    fig.add_trace(go.Scatter(
        x=df11['专业名称'],
        y=df11['周访问量'],
        name='周访问量',
        mode='markers+text+lines',
        marker_color='black',
        marker_size=10,
        textposition='top center',
        line=dict(color='orange', dash='dash'),
        yaxis='y2'
    ))
    fig.update_layout(
        height=450,
        width=600,
        title='本科热门专业TOP20',
        xaxis_title="专业名称",
        yaxis_title="总访问量",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black",
        ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
        yaxis2=dict(showgrid=True, overlaying='y', side='right', title='周访问量'),
        legend=dict(yanchor="top",
                    y=1.15,
                    xanchor="left",
                    x=0.78)
    )
    py.offline.plot(fig, filename="本科热门专业TOP20.html", auto_open=False)
    with open("本科热门专业TOP20.html", encoding="utf8", mode="r") as f:
        plot_all4 = "".join(f.readlines())
    junior = pd.read_csv('./专业数据_专科(高职).csv', encoding='gbk')
    c_name2 = ['专业名称', '学制', '一级名称', '二级名称', '三级名称', '学位',
               '平均薪资', '女生比例', '周访问量', '月访问量', '总访问量']
    regular.columns = c_name2
    junior = junior.loc[:, e_name]
    junior.columns = c_name2
    import plotly.graph_objs as go
    fig = go.Figure()
    df12 = junior.sort_values(by='总访问量', ascending=False)[:20]
    fig.add_trace(go.Bar(
        x=df12['专业名称'],
        y=df12['总访问量'],
        name='总访问量',
        marker_color='#009473',
        textposition='inside',
        yaxis='y1'
    ))
    fig.add_trace(go.Scatter(
        x=df12['专业名称'],
        y=df12['周访问量'],
        name='周访问量',
        mode='markers+text+lines',
        marker_color='black',
        marker_size=10,
        textposition='top center',
        line=dict(color='orange', dash='dash'),
        yaxis='y2'
    ))
    fig.update_layout(
        height=450,
        width=600,
        title='专科(高职)热门专业TOP20',
        xaxis_title="专业名称",
        yaxis_title="总访问量",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black",
        ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
        yaxis2=dict(showgrid=True, overlaying='y', side='right', title='周访问量'),
        legend=dict(yanchor="top",
                    y=1.15,
                    xanchor="left",
                    x=0.78)
    )
    py.offline.plot(fig, filename="专科(高职)热门专业TOP20.html", auto_open=False)
    with open("专科(高职)热门专业TOP20.html", encoding="utf8", mode="r") as f:
        plot_all5 = "".join(f.readlines())
    return render_template(
        "hot_major.html",
        tu3=plot_all4,
        tu4=plot_all5,
        hotmajor=hotmajor,
        select=select,
    )

@app.route('/major')
# 专业热度与平均薪资
def major():
    junior = pd.read_csv('./专业数据_专科(高职).csv', encoding='gbk')
    e_name = ['name', 'limit_year', 'level1_name', 'level2_name', 'level3_name',
              'degree', 'salaryavg', 'girl_rate', 'view_week', 'view_month', 'view_total']
    c_name2 = ['专业名称', '学制', '一级名称', '二级名称', '三级名称', '学位',
               '平均薪资', '女生比例', '周访问量', '月访问量', '总访问量']
    junior = junior.loc[:, e_name]
    junior.columns = c_name2
    df15 = junior.copy()
    df15['平均薪资'] = df15['平均薪资'].map(lambda x: np.nan if x == 0 else x)
    df15['女生比例'] = df15['女生比例'].map(lambda x: np.nan if x == 0 else x)
    for column in ['平均薪资', '女生比例']:
        mean_val = int(df15[column].mean())
        df15[column].fillna(mean_val, inplace=True)
    fig = px.sunburst(df15,
                      path=['二级名称', '三级名称'],
                      values='总访问量',
                      color='平均薪资',
                      hover_data=['女生比例'],
                      color_continuous_scale='RdBu')
    fig.update_layout(
        height=450,
        width=600,
        title='专科(高职)学科、平均薪资与总访问量比例图',
        font=dict(
            size=12,
            color="Black", ),
        plot_bgcolor="#fafafa",
    )
    py.offline.plot(fig, filename="专科(高职)学科、平均薪资与总访问量比例图.html", auto_open=False)
    with open("专科(高职)学科、平均薪资与总访问量比例图.html", encoding="utf8", mode="r") as f:
        plot_all5 = "".join(f.readlines())
    regular = pd.read_csv('./专业数据_本科.csv', encoding='gbk')
    e_name = ['name', 'limit_year', 'level1_name', 'level2_name', 'level3_name',
              'degree', 'salaryavg', 'girl_rate', 'view_week', 'view_month', 'view_total']
    regular = regular.loc[:, e_name]
    c_name2 = ['专业名称', '学制', '一级名称', '二级名称', '三级名称', '学位',
               '平均薪资', '女生比例', '周访问量', '月访问量', '总访问量']
    regular.columns = c_name2
    df14 = regular.copy()
    df14['平均薪资'] = df14['平均薪资'].map(lambda x: np.nan if x == 0 else x)
    df14['女生比例'] = df14['女生比例'].map(lambda x: np.nan if x == 0 else x)
    for column in ['平均薪资', '女生比例']:
        mean_val = int(df14[column].mean())
        df14[column].fillna(mean_val, inplace=True)
    fig = px.sunburst(df14,
                      path=['二级名称', '三级名称'],
                      values='总访问量',
                      color='平均薪资',
                      color_continuous_scale='RdBu')
    fig.update_layout(
        height=450,
        width=600,
        title='本科学科、平均薪资与总访问量比例图',
        # template='ggplot2',
        font=dict(
            size=12,
            color="Black",),
        plot_bgcolor="#fafafa",
    )
    py.offline.plot(fig, filename="本科学科、平均薪资与总访问量比例图.html", auto_open=False)
    with open("本科学科、平均薪资与总访问量比例图.html", encoding="utf8", mode="r") as f:
        plot_all17 = "".join(f.readlines())
    # 工学
    df14 = regular.copy()
    df14 = regular.query("二级名称 == '工学'")
    df14['平均薪资'] = df14['平均薪资'].map(lambda x: np.nan if x == 0 else x)
    df14['女生比例'] = df14['女生比例'].map(lambda x: np.nan if x == 0 else x)
    for column in ['平均薪资', '女生比例']:
        mean_val = int(df14[column].mean())
        df14[column].fillna(mean_val, inplace=True)
    fig = px.sunburst(df14,
                      path=['二级名称', '三级名称'],
                      values='总访问量',
                      color='平均薪资',
                      color_continuous_scale='RdBu')
    fig.update_layout(
        height=450,
        width=600,
        title='工学学科、平均薪资与总访问量比例图',
        font=dict(
            size=12,
            color="Black", ),
        plot_bgcolor="#fafafa",
    )
    py.offline.plot(fig, filename="工学学科、平均薪资与总访问量比例图.html", auto_open=False)
    with open("工学学科、平均薪资与总访问量比例图.html", encoding="utf8", mode="r") as f:
        plot_all_gongxue = "".join(f.readlines())
    df14 = regular.copy()
    df14 = regular.query("二级名称 == '理学'")
    df14['平均薪资'] = df14['平均薪资'].map(lambda x: np.nan if x == 0 else x)
    df14['女生比例'] = df14['女生比例'].map(lambda x: np.nan if x == 0 else x)
    for column in ['平均薪资', '女生比例']:
        mean_val = int(df14[column].mean())
        df14[column].fillna(mean_val, inplace=True)
    fig = px.sunburst(df14,
                      path=['二级名称', '三级名称'],
                      values='总访问量',
                      color='平均薪资',
                      color_continuous_scale='RdBu')
    fig.update_layout(
        height=450,
        width=600,
        title='理学学科、平均薪资与总访问量比例图',
        font=dict(
            size=12,
            color="Black", ),
        plot_bgcolor="#fafafa",
    )
    py.offline.plot(fig, filename="理学学科、平均薪资与总访问量比例图.html", auto_open=False)
    with open("理学学科、平均薪资与总访问量比例图.html", encoding="utf8", mode="r") as f:
        plot_all_lixue = "".join(f.readlines())
    df15 = junior.copy()
    df15 = junior.query("二级名称 == '医药卫生大类'")
    df15['平均薪资'] = df15['平均薪资'].map(lambda x: np.nan if x == 0 else x)
    df15['女生比例'] = df15['女生比例'].map(lambda x: np.nan if x == 0 else x)
    for column in ['平均薪资', '女生比例']:
        mean_val = int(df15[column].mean())
        df15[column].fillna(mean_val, inplace=True)
    fig = px.sunburst(df15,
                      path=['二级名称', '三级名称'],
                      values='总访问量',
                      color='平均薪资',
                      hover_data=['女生比例'],
                      color_continuous_scale='RdBu')
    fig.update_layout(
        height=450,
        width=600,
        title='医药卫生大类学科、平均薪资与总访问量比例图',
        font=dict(
            size=12,
            color="Black", ),
        plot_bgcolor="#fafafa",
    )
    py.offline.plot(fig, filename="医药卫生大类学科、平均薪资与总访问量比例图.html", auto_open=False)
    with open("医药卫生大类学科、平均薪资与总访问量比例图.html", encoding="utf8", mode="r") as f:
        plot_all_yiyao = "".join(f.readlines())
    df15 = junior.copy()
    df15 = junior.query("二级名称 == '交通运输大类'")
    df15['平均薪资'] = df15['平均薪资'].map(lambda x: np.nan if x == 0 else x)
    df15['女生比例'] = df15['女生比例'].map(lambda x: np.nan if x == 0 else x)
    for column in ['平均薪资', '女生比例']:
        mean_val = int(df15[column].mean())
        df15[column].fillna(mean_val, inplace=True)
    fig = px.sunburst(df15,
                      path=['二级名称', '三级名称'],
                      values='总访问量',
                      color='平均薪资',
                      hover_data=['女生比例'],
                      color_continuous_scale='RdBu')
    fig.update_layout(
        height=450,
        width=600,
        title='交通运输大类学科、平均薪资与总访问量比例图',
        font=dict(
            size=12,
            color="Black", ),
        plot_bgcolor="#fafafa",
    )
    py.offline.plot(fig, filename="交通运输大类学科、平均薪资与总访问量比例图.html", auto_open=False)
    with open("交通运输大类学科、平均薪资与总访问量比例图.html", encoding="utf8", mode="r") as f:
        plot_all_jiaotong = "".join(f.readlines())
    return render_template(
        'major.html',
        tu4=plot_all5,
        tu17=plot_all17,
        tu_gongxue=plot_all_gongxue,
        tu_lixue=plot_all_lixue,
        tu_yiyao=plot_all_yiyao,
        tu_jiaotong=plot_all_jiaotong,
    )

hangye = [{'数学与应用数据':'a'},{'计算机科学与技术':'b'},{'电磁场与无线技术':'c'}]
@app.route('/work', methods=['GET', 'POST'])
def work():
    select = request.form.get('comp_select')
    # 就业前景
    # 数学
    professional_name = "数学与应用数据"
    employment = [{"name": "教育培训", "rate": 27.57},
                  {"name": "金融投资", "rate": 9.09},
                  {"name": "IT软件", "rate": 7.88},
                  {"name": "互联网", "rate": 5.00},
                  {"name": "房地产", "rate": 4.38},
                  {"name": "电子技术", "rate": 3.63},
                  {"name": "系统集成", "rate": 3.24},
                  {"name": "快消", "rate": 2.15},
                  {"name": "批发零售", "rate": 0.26},
                  {"name": "其他行业", "rate": 36.80}]
    df_employment = pd.DataFrame(employment)
    import plotly.graph_objs as go
    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=df_employment['name'],
        y=df_employment['rate'],
        name='比率',
        marker_color='#20B2AA',
        textposition='outside',
        text=df_employment.rate,
    ))
    fig.update_traces(texttemplate='%{text}%')
    fig.update_layout(
        height=450,
        width=600,
        title='【数学与应用数学】就业行业分布',
        xaxis_title="就业行业",
        yaxis_title="就业百分比",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black", ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
    )
    py.offline.plot(fig, filename="【数学与应用数学】就业行业分布.html", auto_open=False)
    with open("【数学与应用数学】就业行业分布.html", encoding="utf8", mode="r") as f:
        plot_all6 = "".join(f.readlines())
    # 计算机科学
    jobs = [['后端开发', 14.2],
            ['技术支持', 10.2],
            ['移动开发', 6.7],
            ['销售业务', 5.8],
            ['测试', 5.3],
            ['其他', 57.8]]
    df_jobs = pd.DataFrame(jobs, columns=['就业岗位', '比例'])
    import plotly.graph_objects as go
    labels = ['后端开发', '技术支持', '移动开发', '销售业务', '测试', '其他']
    values = [14.2, 10.2, 6.7, 5.8, 5.3, 57.8]
    fig = go.Figure(data=[go.Pie(labels=labels, values=values,
                                 textinfo='label+percent', hole=.4)])
    fig.update_layout(
        title='【计算机科学与技术】就业岗位分布',
        template='ggplot2',
        font=dict(
            size=12,
            color="Black", ))
    py.offline.plot(fig, filename="【计算机科学与技术】就业岗位分布.html", auto_open=False)
    with open("【计算机科学与技术】就业岗位分布.html", encoding="utf8", mode="r") as f:
        plot_all_jisuanji = "".join(f.readlines())
    # 电磁场与无线技术
    labels = ['电子/电器通用技术', '通信工程', '销售业务', '项目管理/协调', '测试', '其他']
    values = [24.70, 13.80, 8.20, 4.90, 3.10, 45.30]
    fig = go.Figure(data=[go.Pie(labels=labels, values=values,
                                 textinfo='label+percent', hole=.4)])
    fig.update_layout(
        title='【电磁场与无线技术】就业岗位分布',
        template='seaborn',
        font=dict(
            size=12,
            color="Black", ))
    py.offline.plot(fig, filename="【电磁场与无线技术】就业岗位分布.html", auto_open=False)
    with open("【电磁场与无线技术】就业岗位分布.html", encoding="utf8", mode="r") as f:
        plot_all_dian = "".join(f.readlines())
    return render_template(
        'work.html',
        tu5=plot_all6,
        tu_jisuanji=plot_all_jisuanji,
        tu_dian=plot_all_dian,
        hangye=hangye,
        select=select,
    )


hotmajor = [{'本科热门专业':'A'},{'专科(高职)热门专业':'B'}]
@app.route('/hot_major_', methods=['GET', 'POST'])
def hot_major_():
    # 热门专业
    select = request.form.get('comp_select')
    regular = pd.read_csv('./专业数据_本科.csv', encoding='gbk')
    e_name = ['name', 'limit_year', 'level1_name', 'level2_name', 'level3_name',
              'degree', 'salaryavg', 'girl_rate', 'view_week', 'view_month', 'view_total']
    regular = regular.loc[:, e_name]
    c_name2 = ['专业名称', '学制', '一级名称', '二级名称', '三级名称', '学位',
               '平均薪资', '女生比例', '周访问量', '月访问量', '总访问量']
    regular.columns = c_name2
    import plotly.graph_objs as go
    fig = go.Figure()
    df11 = regular.sort_values(by='总访问量', ascending=False)[:20]
    fig.add_trace(go.Bar(
        x=df11['专业名称'],
        y=df11['总访问量'],
        name='总访问量',
        marker_color='#009473',
        textposition='inside',
        yaxis='y1'
    ))
    fig.add_trace(go.Scatter(
        x=df11['专业名称'],
        y=df11['周访问量'],
        name='周访问量',
        mode='markers+text+lines',
        marker_color='black',
        marker_size=10,
        textposition='top center',
        line=dict(color='orange', dash='dash'),
        yaxis='y2'
    ))
    fig.update_layout(
        height=450,
        width=600,
        title='本科热门专业TOP20',
        xaxis_title="专业名称",
        yaxis_title="总访问量",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black",
        ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
        yaxis2=dict(showgrid=True, overlaying='y', side='right', title='周访问量'),
        legend=dict(yanchor="top",
                    y=1.15,
                    xanchor="left",
                    x=0.78)
    )
    py.offline.plot(fig, filename="本科热门专业TOP20.html", auto_open=False)
    with open("本科热门专业TOP20.html", encoding="utf8", mode="r") as f:
        plot_all4 = "".join(f.readlines())
    junior = pd.read_csv('./专业数据_专科(高职).csv', encoding='gbk')
    c_name2 = ['专业名称', '学制', '一级名称', '二级名称', '三级名称', '学位',
               '平均薪资', '女生比例', '周访问量', '月访问量', '总访问量']
    regular.columns = c_name2
    junior = junior.loc[:, e_name]
    junior.columns = c_name2
    import plotly.graph_objs as go
    fig = go.Figure()
    df12 = junior.sort_values(by='总访问量', ascending=False)[:20]
    fig.add_trace(go.Bar(
        x=df12['专业名称'],
        y=df12['总访问量'],
        name='总访问量',
        marker_color='#009473',
        textposition='inside',
        yaxis='y1'
    ))
    fig.add_trace(go.Scatter(
        x=df12['专业名称'],
        y=df12['周访问量'],
        name='周访问量',
        mode='markers+text+lines',
        marker_color='black',
        marker_size=10,
        textposition='top center',
        line=dict(color='orange', dash='dash'),
        yaxis='y2'
    ))
    fig.update_layout(
        height=450,
        width=600,
        title='专科(高职)热门专业TOP20',
        xaxis_title="专业名称",
        yaxis_title="总访问量",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black",
        ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
        yaxis2=dict(showgrid=True, overlaying='y', side='right', title='周访问量'),
        legend=dict(yanchor="top",
                    y=1.15,
                    xanchor="left",
                    x=0.78)
    )
    py.offline.plot(fig, filename="专科(高职)热门专业TOP20.html", auto_open=False)
    with open("专科(高职)热门专业TOP20.html", encoding="utf8", mode="r") as f:
        plot_all5 = "".join(f.readlines())
    return render_template(
        "hot_major_.html",
        tu3=plot_all4,
        tu4=plot_all5,
        hotmajor=hotmajor,
        select=select,
    )

hangye = [{'数学与应用数据':'a'},{'计算机科学与技术':'b'},{'电磁场与无线技术':'c'}]
@app.route('/works', methods=['GET', 'POST'])
def works():
    select = request.form.get('comp_select')
    # 就业前景
    # 数学
    professional_name = "数学与应用数据"
    employment = [{"name": "教育培训", "rate": 27.57},
                  {"name": "金融投资", "rate": 9.09},
                  {"name": "IT软件", "rate": 7.88},
                  {"name": "互联网", "rate": 5.00},
                  {"name": "房地产", "rate": 4.38},
                  {"name": "电子技术", "rate": 3.63},
                  {"name": "系统集成", "rate": 3.24},
                  {"name": "快消", "rate": 2.15},
                  {"name": "批发零售", "rate": 0.26},
                  {"name": "其他行业", "rate": 36.80}]
    df_employment = pd.DataFrame(employment)
    import plotly.graph_objs as go
    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=df_employment['name'],
        y=df_employment['rate'],
        name='比率',
        marker_color='#20B2AA',
        textposition='outside',
        text=df_employment.rate,
    ))
    fig.update_traces(texttemplate='%{text}%')
    fig.update_layout(
        height=450,
        width=600,
        title='【数学与应用数学】就业行业分布',
        xaxis_title="就业行业",
        yaxis_title="就业百分比",
        template='ggplot2',
        font=dict(
            size=12,
            color="Black", ),
        xaxis=dict(showgrid=False),
        yaxis=dict(showgrid=False),
        plot_bgcolor="#fafafa",
    )
    py.offline.plot(fig, filename="【数学与应用数学】就业行业分布.html", auto_open=False)
    with open("【数学与应用数学】就业行业分布.html", encoding="utf8", mode="r") as f:
        plot_all6 = "".join(f.readlines())
    # 计算机科学
    jobs = [['后端开发', 14.2],
            ['技术支持', 10.2],
            ['移动开发', 6.7],
            ['销售业务', 5.8],
            ['测试', 5.3],
            ['其他', 57.8]]
    df_jobs = pd.DataFrame(jobs, columns=['就业岗位', '比例'])
    import plotly.graph_objects as go
    labels = ['后端开发', '技术支持', '移动开发', '销售业务', '测试', '其他']
    values = [14.2, 10.2, 6.7, 5.8, 5.3, 57.8]
    fig = go.Figure(data=[go.Pie(labels=labels, values=values,
                                 textinfo='label+percent', hole=.4)])
    fig.update_layout(
        height=450,
        width=600,
        title='【计算机科学与技术】就业岗位分布',
        template='ggplot2',
        font=dict(
            size=12,
            color="Black", ))
    py.offline.plot(fig, filename="【计算机科学与技术】就业岗位分布.html", auto_open=False)
    with open("【计算机科学与技术】就业岗位分布.html", encoding="utf8", mode="r") as f:
        plot_all_jisuanji = "".join(f.readlines())
    # 电磁场与无线技术
    labels = ['电子/电器通用技术', '通信工程', '销售业务', '项目管理/协调', '测试', '其他']
    values = [24.70, 13.80, 8.20, 4.90, 3.10, 45.30]
    fig = go.Figure(data=[go.Pie(labels=labels, values=values,
                                 textinfo='label+percent', hole=.4)])
    fig.update_layout(
        height=450,
        width=600,
        title='【电磁场与无线技术】就业岗位分布',
        template='seaborn',
        font=dict(
            size=12,
            color="Black", ))
    py.offline.plot(fig, filename="【电磁场与无线技术】就业岗位分布.html", auto_open=False)
    with open("【电磁场与无线技术】就业岗位分布.html", encoding="utf8", mode="r") as f:
        plot_all_dian = "".join(f.readlines())
    return render_template(
        'works.html',
        tu5=plot_all6,
        tu_jisuanji=plot_all_jisuanji,
        tu_dian=plot_all_dian,
        hangye=hangye,
        select=select,
    )

if __name__ == '__main__':
    app.run(debug=True)
